﻿using ITSM.Model;
using ITSM.Model.Entity;
using ITSM.Model.Model;
using ITSM.Service.Utils;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SqlSugar.DistributedSystem.Snowflake;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using static System.Net.Mime.MediaTypeNames;

namespace ITSM.Service
{
    public class WxMessage : BaseDB, IWxMessage
    {
        private readonly ILogger _log;
        public WxMessage(ILogger<WxMessage> log)
        {
            _log = log;
        }

        async public Task<bool> SendMessage(M_Template data)
        {
            try
            {
                var todoItemJson = JsonHelpUtil.JsonSerializer(data); // using static System.Net.Mime.MediaTypeNames;
                return await SendMessage(todoItemJson);
            }
            catch (Exception)
            {
                return false;
            }
        }

        async public Task<bool> SendMessage(M_TemplateTwo data)
        {
            try
            {
                var todoItemJson = JsonHelpUtil.JsonSerializer(data); // using static System.Net.Mime.MediaTypeNames;
                return await SendMessage(todoItemJson);
            }
            catch (Exception)
            {
                return false;
            }
        }
        async private Task<bool> SendMessage(string stringContent)
        {
            try
            {
                int flag = 3;
                while (flag > 0)
                {
                    flag--;
                    string token = await new WxToken().GetToken();
                    //WX接口地址，发送模板信息
                    string wx_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
                    var todoItemJson = new StringContent(stringContent, Encoding.UTF8, Application.Json); // using static System.Net.Mime.MediaTypeNames;

                    var httpClient = HttpClientFactory.Create();
                    //发送请求
                    using var httpResponseMessage = await httpClient.PostAsync(wx_url, todoItemJson);

                    //判断请求是否成功
                    if (httpResponseMessage.IsSuccessStatusCode)
                    {
                        //获取数据流
                        using var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync();
                        //转换成string
                        StreamReader reader = new(contentStream);
                        string text = reader.ReadToEnd();
                        if (text.Contains("errcode", StringComparison.CurrentCulture))
                        {
                            ReturnWXCodErr? err = JsonHelpUtil.JsonDeserialize<ReturnWXCodErr>(text);
                            if (err == null)
                            {
                                continue;
                            }
                            switch (err.errcode)
                            {
                                case 40001:
                                case 40014:
                                case 41001:
                                case 42001:
                                    int num = db.Updateable<RYD_FieldDict>().Where(res => res.RYD_FieldName == "wxToken" && res.RYD_State == 1).SetColumns(res => res.RYD_ModifyTime == Convert.ToDateTime("2022-01-01")).ExecuteCommand();
                                    _log.LogError("发送微信公众号模板信息失败，错误码:"+err.errcode+"。信息:"+err.errmsg+"。json内容:"+ stringContent);
                                    break;
                                case 0:
                                    return true;
                                default:
                                    _log.LogError("发送微信公众号模板信息失败，错误码:" + err.errcode + "。信息:" + err.errmsg + "。json内容:" + stringContent);

                                    break;
                            }
                        }
                        ////转换成实体
                        //WXOAuth? wxOAuth = JsonHelpUtil.JsonDeserialize<WXOAuth>(text);
                        //if (wxOAuth != null)
                        //{


                        //}
                    }
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }

    public class ReturnWXCodErr
    {
        public int errcode { get; set; }
#pragma warning disable CS8618 // 在退出构造函数时，不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。
        public string errmsg { get; set; }
#pragma warning restore CS8618 // 在退出构造函数时，不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。
    }
}
